import type { FetchAPI, ServerResult, User, UserPermissionService, UserRoleService, UserService } from '../../server/interface'
import { createFetch } from './Fetch'

const baseUrl = location.pathname
const Fetch = createFetch({ baseUrl })

export const api_common: {
    loginUser: FetchAPI<undefined, User>;
} = {
    loginUser: () => Fetch("/loginUser", null, { cache: 'no-cache' }).then((_res) => {
        const res = _res as ServerResult<User>
        if (res.success && res.data) {
            res.data.permissions = new Set(res.data?.permissions ?? [])
        }
        return res
    })
}

export const api_user: {
    list: UserService["userList"];
    create: UserService["userCreate"];
    delete: UserService["userDelete"];
    update: UserService["userUpdate"];
    updatePassword: FetchAPI<{ newPassword: string }>;
} = {
    list: (data) => Fetch("/user.list", data),
    create: (data) => Fetch("/user.create", data),
    delete: (data) => Fetch("/user.delete", data),
    update: (data) => Fetch("/user.update", data),
    updatePassword: (data) => Fetch("/user.updatePassword", data),
}

export const api_role: {
    list: UserRoleService['roleList'];
    create: UserRoleService['roleCreate'];
    delete: UserRoleService['roleDelete'];
    update: UserRoleService['roleUpdate'];
} = {
    list: (data) => Fetch("/role.list", data),
    create: (data) => Fetch("/role.create", data),
    delete: (data) => Fetch("/role.delete", data),
    update: (data) => Fetch("/role.update", data),
}

export const api_permission: {
    list: UserPermissionService['permissionList'];
    create: UserPermissionService['permissionCreate'];
    delete: UserPermissionService['permissionDelete'];
    update: UserPermissionService['permissionUpdate'];
} = {
    list: (data) => Fetch("/permission.list", data),
    create: (data) => Fetch("/permission.create", data),
    delete: (data) => Fetch("/permission.delete", data),
    update: (data) => Fetch("/permission.update", data),
}